<template>
  <div>
    <div class="layout-padding w60" style="left: 40%">
      <div class="layout-padding-auto layout-padding-view">

        <el-row class="ml10" v-show="showSearch">
          <el-form :inline="true" :model="state.queryForm" ref="queryRef">

            <el-form-item label="社保卡" prop="medicalCard" style="max-width: 180px">
              <el-input v-model="state.queryForm.medicalCard" placeholder="请输入社保卡"/>
            </el-form-item>
            <el-form-item label="姓名" prop="name" style="max-width: 180px">
              <el-input placeholder="请输入姓名" v-model="state.queryForm.name"/>
            </el-form-item>
            <el-form-item label="村" prop="village" style="max-width: 180px">
              <el-select v-model="state.queryForm.village" placeholder="请选择村" clearable>
                <el-option :label="item.name" :value="item.id" v-for="(item, index) in village"
                           :key="index"/>
              </el-select>
            </el-form-item>
            <el-form-item label="家庭医生" prop="familyDoctor" style="max-width: 180px">
              <el-select v-model="state.queryForm.familyDoctor" placeholder="请选择家庭医生" clearable>
                <el-option :key="item.userId" :label="item.name" :value="item.userId"
                           v-for="item in doctorList"/>
              </el-select>
            </el-form-item>
            <el-form-item label="签到时间" prop="signTime" style="max-width: 220px">
              <el-date-picker type="date" placeholder="请选择签到时间" v-model="state.queryForm.signTime"
                              :value-format="dateStr"></el-date-picker>
            </el-form-item>
            <el-form-item label="签到状态" prop="signStatus" style="max-width: 200px">
              <el-select
                  v-model="state.queryForm.signStatus"
                  placeholder="选择签到状态"
                  clearable
              >
                <el-option label="已签到" value="1"/>
                <el-option label="未签到" value="0"/>
              </el-select>
              <!--              <el-input placeholder="签到状态" style="max-width: 180px" v-model="state.queryForm.signStatus"/>-->
            </el-form-item>
            <el-form-item>
              <el-button @click="searchData" formDialogRef icon="search" type="primary">
                {{ $t('common.queryBtn') }}
              </el-button>
              <el-button @click="resetQuery" formDialogRef icon="Refresh">{{
                  $t('common.resetBtn')
                }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-row>


        <el-row>
          <el-button icon="Platform" type="primary" class="ml10" @click="startExam"> 进行体检</el-button>
          <div class="mb8" style="width: 100%">
            <right-toolbar v-model:showSearch="showSearch" :export="'blood_bloodxExamCustomer_export'"
                           @exportExcel="exportExcel" class="ml10 mr20" style="float: right"
                           @queryTable="refreshData"></right-toolbar>
          </div>
        </el-row>

        <el-table size="small" style="width: 100%" :data="state.dataList" v-loading="state.loading" border
                  :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
                  highlight-current-row @current-change="handleCurrentChange" @sort-change="sortChangeHandle">
          <el-table-column type="index" label="#" width="40"/>
<!--          <el-table-column prop="examNo" label="体检编号" show-overflow-tooltip/>-->
          <el-table-column prop="labelNo" label="标签序号" show-overflow-tooltip/>
          <el-table-column prop="name" label="姓名" show-overflow-tooltip/>
          <el-table-column prop="birthday" label="出生日期" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.birthday?.substring(0, 10) }}
            </template>
          </el-table-column>
          <el-table-column prop="age" label="年龄" show-overflow-tooltip></el-table-column>
          <!--					<el-table-column prop="sex" label="性别" width="70" show-overflow-tooltip>-->
          <!--						<template #default="scope">-->
          <!--							<dict-tag :options="gender" :value="scope.row.sex"></dict-tag>-->
          <!--						</template>-->
          <!--					</el-table-column>-->
          <!--    <el-table-column prop="icCard" label="身份证号" show-overflow-tooltip/>-->
          <el-table-column prop="tel" label="联系电话" show-overflow-tooltip/>
          <!--					<el-table-column prop="address" label="地址" show-overflow-tooltip />-->
          <el-table-column prop="villageName" label="村" show-overflow-tooltip>
            <!-- <template #default="scope">
              <dict-tag :options="village" :value="scope.row.village"></dict-tag>
            </template> -->
          </el-table-column>
          <el-table-column prop="medicalCard" label="社保卡号" show-overflow-tooltip/>
          <el-table-column prop="healthStatus" label="管理状态" show-overflow-tooltip>
            <template #default="scope">
              <dict-tag :options="bloodx_health" :value="scope.row.healthStatus"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column prop="doctorName" label="家庭医生" show-overflow-tooltip>
            <!-- <template #default="scope">
              <dict-tag :options="family_doctor" :value="scope.row.familyDoctor"></dict-tag>
            </template> -->
          </el-table-column>
          <el-table-column prop="signTime" label="签到时间" show-overflow-tooltip/>
          <el-table-column prop="signStatus" label="签到状态" show-overflow-tooltip fixed="right">
            <template #default="scope">
              <el-tag v-if="scope.row.signStatus == '1'" type="success">已签到</el-tag>
              <el-tag v-else type="danger">未签到</el-tag>
              <!--              <dict-tag :options="bloodx_sign" :value="scope.row.signStatus"></dict-tag>-->
            </template>
          </el-table-column>
        </el-table>
        <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle"
                    v-bind="state.pagination"/>
        <!-- 编辑、新增  -->
        <form-dialog ref="formDialogRef" @refresh="getDataList(false)"/>

        <!--        <el-dialog title="进行体检" v-model="visibleExamForm" :before-close="beforeClose"-->
        <!--                   :close-on-click-modal="false" draggable>-->
        <exam-form ref="examFormRef"  @refresh="getDataList(false)"/>
        <!--        </el-dialog>-->
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="systemBloodxExamCustomer">
import {BasicTableProps, useTable} from '/@/hooks/table';
import {fetchList} from '/@/api/blood/bloodxExamCustomer';
import {useMessage} from '/@/hooks/message';
import {useDict} from '/@/hooks/dict';
import {getDoctorList} from "/@/api/information/village";
import {sysVillageList} from "/@/api/blood/bloodxCustomer";

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const ExamForm = defineAsyncComponent(() => import('../../../components/examForm/index.vue'));

// 定义查询字典
// 定义字典
const {bloodx_health} = useDict('bloodx_health');

// const {bloodx_sign} = useDict('bloodx_sign')
// 定义变量内容
const formDialogRef = ref();
const examFormRef = ref();
const queryRef = ref();
// 搜索变量
// const queryRef = ref()
const showSearch = ref(true);
// const visibleExamForm = ref(false);
const doctorList = ref<any[]>([]);
const village = ref<any[]>([]);
// 多选变量
// const selectObjs = ref([]) as any
// const multiple = ref(true)
// const visible = ref(false)

// const examInfo = ref({});
const currentRow = ref({
  examId: '',
  examNo: '',
  labelNo: '',
  id: '',
  name: '',
  birthday: '',
  age: null,
  sex: '',
  icCard: '',
  tel: '',
  address: '',
  village: '',
  localCard: '',
  medicalCard: '',
  healthStatus: '',
  familyDoctor: '',
  signStatus: '',
});
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: fetchList,
  createdIsNeed: false,
});

//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state);

// 清空搜索条件
// const resetQuery = () => {
//   // 清空搜索条件
//   queryRef.value?.resetFields()
//   // 清空多选
//   selectObjs.value = []
//   getDataList()
// }

const refreshData = () => {
  if (state.queryForm.examId === undefined || state.queryForm.examId === "" || state.queryForm.examId === null) {
    useMessage().error("请选择体检任务")
    return
  }
  getDataList();
};

// 导出excel
const exportExcel = () => {
  if (state.queryForm.examId === undefined || state.queryForm.examId === "" || state.queryForm.examId === null) {
    useMessage().error("请选择体检任务")
    return
  }
  downBlobFile('/blood/bloodxExamCustomer/export', Object.assign(state.queryForm), '体检患者.xlsx');
};

const searchData = () => {
  if (state.queryForm.examId === undefined || state.queryForm.examId === "" || state.queryForm.examId === null) {
    useMessage().error("请选择体检任务")
    return
  }

  if (state.queryForm.signTime && state.queryForm.signTime.indexOf(':') === -1) {
    state.queryForm.signTime += ' 00:00:00';
  }

  getDataList();
}

// 清空搜索条件
const resetQuery = () => {
  if (state.queryForm.examId === undefined || state.queryForm.examId === "" || state.queryForm.examId === null) {
    useMessage().error("请选择体检任务")
    return
  }
  // 清空搜索条件
  queryRef.value?.resetFields();
  // 清空多选
  getDataList();
};
const getdoctorList = () => {
  getDoctorList().then((res) => {
    doctorList.value = res.data;
  });

  sysVillageList().then((res) => {
    village.value = res.data;
  });
};
// 多选事件
// const selectionChangHandle = (objs: { id: string }[]) => {
//   selectObjs.value = objs.map(({id}) => id);
//   multiple.value = !objs.length;
// };

// 删除操作
// const handleDelete = async (ids: string[]) => {
//   try {
//     await useMessageBox().confirm('此操作将永久删除');
//   } catch {
//     return;
//   }
//
//   try {
//     await delObjs(ids);
//     getDataList();
//     useMessage().success('删除成功');
//   } catch (err: any) {
//     useMessage().error(err.msg);
//   }
// };

// 打开变发证页面
const openExamData = (row: any) => {
  state.queryForm = {};
  currentRow.value = {
    examId: '',
    examNo: '',
    labelNo: '',
    id: '',
    name: '',
    birthday: '',
    age: null,
    sex: '',
    icCard: '',
    tel: '',
    address: '',
    village: '',
    localCard: '',
    medicalCard: '',
    healthStatus: '',
    familyDoctor: '',
    signStatus: '',
    // isDialog: false,
  };
  if (row) {
    state.queryForm = {examId: row.id};
  }

  if (state.queryForm.examId === undefined || state.queryForm.examId === "" || state.queryForm.examId === null) {
    // 清空数据
    state.dataList = [];
    state.pagination.total = 0;
    return
  }
  getDataList();
};

// 创建时

onMounted(() => {
  getdoctorList()
});

const startExam = () => {
  if (currentRow.value.id === '') {
    useMessage().warning('请选择患者');
    return;
  }

  // console.log(currentRow.value)
  // if (currentRow.value.signStatus == '1') {
  //   useMessage().warning('已签到')
  //   return
  // }
  // currentRow.value.isDialog = true;
  // visibleExamForm.value = true;
  examFormRef.value.openDialog(currentRow.value.medicalCard,currentRow.value.examId);
};

const handleCurrentChange = (row: any) => {
  if (row) {
    // console.log(row)
    currentRow.value = row;
  } else {
    currentRow.value = {
      examId: '',
      examNo: '',
      labelNo: '',
      id: '',
      name: '',
      birthday: '',
      age: null,
      sex: '',
      icCard: '',
      tel: '',
      address: '',
      village: '',
      localCard: '',
      medicalCard: '',
      healthStatus: '',
      familyDoctor: '',
      signStatus: '',
      // isDialog: false,
    };
  }
};

// const beforeClose = (done: () => void) => {
//   done();
//   getDataList(false);
// };

// 暴露变量
defineExpose({
  openExamData,
});
</script>
